﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using JY.Common.Enums;
using JY.Wpf.Controls.ControlHelpers;
using JY.Wpf.Core.Enums;
using JY.Wpf.Core.Models;
using JY.Wpf.Core.Tools;

namespace JY.Wpf.Controls.Controls
{
    /// <summary>
    /// 警告消息控件
    /// </summary>
    public class WarningMessageBar : ContentControl
    {
        #region # 变量 
        private const string ActivateStoryboardName = "ActivateStoryboard";
        private const string DeactivateStoryboardName = "DeactivateStoryboard";
        private List<WarningMessage> _warningMessages = new List<WarningMessage>();
        private DispatcherTimer _messageActiveTimer;
        private DispatcherTimer _messageDeactivateTimer;
        private Action<MessageType> _deactivateMessageAction;
        /// <summary>
        /// 激活消息时间
        /// </summary>
        public TimeSpan ActivateStoryboardDuration { get; private set; }

        /// <summary>
        /// 失活消息时间
        /// </summary>

        public TimeSpan DeactivateStoryboardDuration { get; private set; } 
        #endregion

        #region # 警告消息——WarningMessage WarningMessage
        /// <summary>
        /// 警告消息
        /// </summary>
        public WarningMessage WarningMessage
        {
            get { return (WarningMessage)GetValue(WarningMessageProperty); }
            set { SetValue(WarningMessageProperty, value); }
        }
        public static readonly DependencyProperty WarningMessageProperty = DependencyProperty.Register("WarningMessage", typeof(WarningMessage), typeof(WarningMessageBar), new PropertyMetadata(default(WarningMessage), WarningMessageChanged));

        #endregion

        #region # 警告消息变更事件
        /// <summary>
        /// 警告消息变更事件
        /// </summary>
        /// <param name="dependencyObject"></param>
        /// <param name="e"></param>
        private static void WarningMessageChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            WarningMessageBar warningMessageBar = dependencyObject as WarningMessageBar;
            warningMessageBar?.ActiveWarningMessage((WarningMessage)e.NewValue);
        } 
        #endregion

        #region # 是否激活显示消息——bool IsActive
        /// <summary>
        /// 是否激活显示消息
        /// </summary>
        public bool IsActive
        {
            get { return (bool)GetValue(IsActiveProperty); }
            set { SetValue(IsActiveProperty, value); }
        }
        public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register(
            nameof(IsActive), typeof(bool), typeof(WarningMessageBar), new PropertyMetadata(default(bool), IsActiveChanged));

        #endregion

        #region # 是否激活警告消息变更事件
        /// <summary>
        /// 是否激活警告消息变更事件
        /// </summary>
        /// <param name="dependencyObject"></param>
        /// <param name="e"></param>
        private static void IsActiveChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            WarningMessageBar warningMessageBar = dependencyObject as WarningMessageBar;
            if (warningMessageBar == null) return;
            if (e.NewValue != null && !(bool)e.NewValue)
            {
                var warningMessage = warningMessageBar._warningMessages.FirstOrDefault();
                warningMessageBar._warningMessages.Remove(warningMessage);
            }
            else if (e.NewValue != null && (bool)e.NewValue)
            {
                //启动失活计时器
                warningMessageBar.DeactivateMessage();
            }
        }
        #endregion

        #region # 激活警告消息——void ActiveWarningMessage(WarningMessage warningMessage)
        /// <summary>
        /// 激活警告消息
        /// </summary>
        /// <param name="warningMessage">警告消息</param>
        private void ActiveWarningMessage(WarningMessage warningMessage)
        {
            if (warningMessage == null || warningMessage.IsDisplayed) return;
            this._warningMessages.Add(warningMessage);
            if (this._warningMessages.Count > 1)
            {
                if (this._messageActiveTimer == null)
                {
                    this._messageActiveTimer = new DispatcherTimer();
                    this._messageActiveTimer.Interval = TimeSpan.FromMilliseconds(1);
                    this._messageActiveTimer.Tick += MessageActiveTimer_Tick;
                }
                this._messageActiveTimer.Start();
            }
            else
            {
                this.Content = warningMessage;
                this.IsActive = true;
                warningMessage.IsDisplayed = true;
            }
        }
        private void MessageActiveTimer_Tick(object sender, EventArgs e)
        {
            if (!this.IsActive)
            {
                this.IsActive = true;
                this.Content = this._warningMessages.FirstOrDefault();
            }

            if (!this._warningMessages.Any())
            {
                this._messageActiveTimer?.Stop();
            }
        }
        #endregion

        #region # 失活警告消息——void DeactivateMessage()
        /// <summary>
        /// 失活警告消息
        /// </summary>
        private void DeactivateMessage()
        {
            if (this._messageDeactivateTimer == null)
            {
                this._messageDeactivateTimer = new DispatcherTimer();
                this._messageDeactivateTimer.Interval = this.ActivateStoryboardDuration + TimeSpan.FromSeconds(2.2);
                this._messageDeactivateTimer.Tick += MessageDeactivateTimer_Tick;
            }
            this._messageDeactivateTimer.Start();
        }

        private void MessageDeactivateTimer_Tick(object sender, EventArgs e)
        {
            this.IsActive = false;
            this.WarningMessage.IsDisplayed = true;
            this._messageDeactivateTimer?.Stop();
            this._deactivateMessageAction?.Invoke(this.WarningMessage.MessageType);
        }
        #endregion

        #region # 应用样式模板——void OnApplyTemplate()
        /// <summary>
        /// 应用样式模板
        /// </summary>
        public override void OnApplyTemplate()
        {
            this.ActivateStoryboardDuration = this.GetStoryboardResourceDuration(ActivateStoryboardName);
            this.DeactivateStoryboardDuration = this.GetStoryboardResourceDuration(DeactivateStoryboardName);

            base.OnApplyTemplate();
        }
        #endregion

        #region # 获取资源样式动画时间——TimeSpan GetStoryboardResourceDuration(string resourceName)
        /// <summary>
        /// 获取资源样式动画时间
        /// </summary>
        /// <param name="resourceName"></param>
        /// <returns></returns>
        private TimeSpan GetStoryboardResourceDuration(string resourceName)
        {
            var storyboard = this.Template.Resources.Contains(resourceName)
                ? (Storyboard)this.Template.Resources[resourceName]
                : null;

            return storyboard != null && storyboard.Duration.HasTimeSpan
                ? storyboard.Duration.TimeSpan
                : new Func<TimeSpan>(() =>
                {
                    System.Diagnostics.Debug.WriteLine(
                        $"Warning, no Duration was specified at root of storyboard '{resourceName}'.");
                    return TimeSpan.Zero;
                })();
        }
        #endregion

        #region # 初始化——void Initialize(object viewModel)
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public static async void Initialize(Action<MessageType> deactivateMessage)
        {
            await Task.Run(() => { Thread.Sleep(TimeSpan.FromMilliseconds(0.1));});
            var window = VisualHelper.GetActiveWindow() ?? Application.Current.MainWindow;
            if (window != null)
            {
                var decorator = VisualHelper.GetChild<AdornerDecorator>(window);
                if (decorator != null)
                {
                    WarningMessageBar warningMessageBar=VisualHelper.GetChild<WarningMessageBar>(decorator);
                    if (warningMessageBar == null)
                    {
                        warningMessageBar = new WarningMessageBar();

                        var binding = new Binding("WarningMessage") { Mode = BindingMode.TwoWay };
                        warningMessageBar.SetBinding(WarningMessageBar.WarningMessageProperty, binding);
                        var layer = decorator.AdornerLayer;
                        if (layer != null)
                        {
                            var container = new AdornerContainer(layer)
                            {
                                Child = warningMessageBar,
                            };
                            layer.Add(container);
                        }
                    }
                    warningMessageBar._deactivateMessageAction = deactivateMessage;
                }
            }
        }
        #endregion
    }
}
